package com.yhg.Service.Impl;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yhg.Order.Bean.Order;
import com.yhg.Product.Bean.Product;
import com.yhg.Service.OrderService;
import com.yhg.feign.ProductFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired  //诸如服务发现
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired //注入负载均衡
    LoadBalancerClient loadBalancerClient;
    @Autowired
    ProductFeignClient productFeignClient;
    @Override
    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallback")
    public Order createOrder(Long productId, Long userId){
        //利用服务发现
//        Product product = getProductFromRemote(productId);
        //利用负载均衡
//        Product product1 = getProductFromRemoteWithLoadBalancer(productId);
        //利用注解式负载均衡
//        Product product1 = getProductFromRemoteWithLoadBalancerAnnotation(productId);
        //使用feign请求数据
        Product product1 = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(0L);
        //需计算
        order.setTotalAmount(product1.getPrice().multiply(new BigDecimal(product1.getNum())));
        order.setNickName("张三");
        order.setAddress("尚硅谷");
        //需查询
        order.setProductList(Arrays.asList(product1));

        return order;
    }
    //blockhandler兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e){
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("未知用户");
        order.setAddress("异常信息"+e.getClass());

        return order;


    }

    //第一版：远程调用算法，利用服务发现DiscoveryClient（代码式rest）
    private Product getProductFromRemote(Long productId){
        //1 获取到商品服务所在的所有机器的ip+port
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        //http://localhost:9002/product/4  远程url
        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
        log.info("远程请求：{}",url);
        //2 给远程发送请求

        Product product =  restTemplate.getForObject(url,Product.class);
        return product;
    }
    //第二版：完成负载均衡远程调用，利用LoadBalancerClient （代码式rest）
    /*
    1 引入负载均衡依赖：spring-cloud-starter-loadbalancer
    2 测试负载均衡API LoadBalancerClient
    3 测试远程调用 RestTemplate
    4 测试负载均衡调用 @LoadBalanced

    思考：如果注册中心宕机，远程调用还能成功吗？
    (1)如果已经调用过一次，如果提供该服务的服务器正常，那么可以调用，因为会放在缓存中
    （2）如果第一次调用，不可以
    **/
    private Product getProductFromRemoteWithLoadBalancer(Long productId){
        //1 获取到商品服务所在的所有机器的ip+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //http://localhost:9002/product/4  远程url
        String url = "http://"+choose.getHost()+":"+choose.getPort()+"/product/"+productId;
        log.info("远程请求：{}",url);
        //2 给远程发送请求

        Product product =  restTemplate.getForObject(url,Product.class);
        return product;
    }
    //第三版：基于注解的负载均衡  （代码式rest）
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId){

        //2 给远程发送请求
        String url = "http://service-product/product/"+productId;
        Product product =  restTemplate.getForObject(url,Product.class);
        return product;
    }
}
